<template>
  <div id="userRegisterPage">
    <h2 class="title">鱼皮 AI 应用生成 - 用户注册</h2>
    <div class="desc">创建账号，开始使用我们的服务</div>
    <a-form :model="formState" name="register" autocomplete="off" @finish="handleSubmit" :rules="formRules">
      <a-form-item name="userAccount" label="账号">
        <a-input v-model:value="formState.userAccount" placeholder="请输入账号" />
      </a-form-item>
      <a-form-item name="userPassword" label="密码">
        <a-input-password v-model:value="formState.userPassword" placeholder="请输入密码" />
      </a-form-item>
      <a-form-item name="checkPassword" label="确认密码">
        <a-input-password v-model:value="formState.checkPassword" placeholder="请再次输入密码" />
      </a-form-item>
      <div class="tips">
        已有账号？
        <RouterLink to="/user/login">去登录</RouterLink>
      </div>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">注册</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { addUser } from '@/api/userController.ts'

// 表单状态
const formState = reactive<API.UserAddRequest>({
  userAccount: '',
  userPassword: '',
  checkPassword: ''
})

// 表单验证规则
const formRules = {
  userAccount: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, message: '账号长度不能少于4个字符', trigger: 'blur' }
  ],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度不能少于8个字符', trigger: 'blur' }
  ],
  checkPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_, value) => {
        if (!value || formState.userPassword === value) {
          return Promise.resolve()
        }
        return Promise.reject(new Error('两次输入的密码不一致'))
      },
      trigger: 'blur'
    }
  ]
}

const router = useRouter()

/**
 * 提交注册表单
 */
const handleSubmit = async () => {
  try {
    // 检查密码是否一致
    if (formState.userPassword !== formState.checkPassword) {
      message.error('两次输入的密码不一致')
      return
    }

    // 调用注册接口
    const res = await addUser({
      userAccount: formState.userAccount,
      userPassword: formState.userPassword
    })

    if (res.data.code === 0) {
      message.success('注册成功，请登录')
      // 跳转到登录页面
      router.push({
        path: '/user/login',
        replace: true
      })
    } else {
      message.error('注册失败：' + (res.data.message || '未知错误'))
    }
  } catch (error) {
    console.error('注册请求失败', error)
    message.error('注册请求失败，请稍后重试')
  }
}
</script>

<style scoped>
#userRegisterPage {
  max-width: 360px;
  margin: 0 auto;
}

.title {
  text-align: center;
  margin-bottom: 16px;
}

.desc {
  text-align: center;
  color: #bbb;
  margin-bottom: 16px;
}

.tips {
  margin-bottom: 16px;
  color: #bbb;
  font-size: 13px;
  text-align: right;
}
</style>
